package com.pubinfo.passbook.common.utils.bank;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@Slf4j
public class BankSignUtil {
  /**
   * 获取请求签名值
   *
   * @param data
   * @param key
   * @return
   */
  public static String getSignature(String data, String key) {
    Mac mac;
    try {
      mac = Mac.getInstance("HmacSHA256");
      SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
      mac.init(secretKey);
      mac.update(data.getBytes(StandardCharsets.UTF_8));
    } catch (Exception e) {
      log.error("获取Signature签名信息异常：", e);
      return null;
    }
    return byte2Hex(mac.doFinal());
  }
  
  /**
   * 将byte转为16进制
   *
   * @param bytes
   * @return
   */
  private static String byte2Hex(byte[] bytes) {
    StringBuilder stringBuffer = new StringBuilder();
    String temp;
    for (byte aByte : bytes) {
      temp = Integer.toHexString(aByte & 0xFF);
      if (temp.length() == 1) {
        // 1得到一位的进行补0操作
        stringBuffer.append("0");
      }
      stringBuffer.append(temp);
    }
    return stringBuffer.toString();
  }
  
  public static void main(String[] args) {
    String str = "{\"payerPartCode\":\"111\",\"payerPartPhone\":\"17326001207\",\"startDate\":\"20210101\",\"endDate\":\"20210501\"}";
    String time = "1626940126614";
    String sign = getSignature(str + time, "xmCpyyC6HGkpxEZnPxFwe8gdYf7347XP");
    System.out.println(sign);
  }
  
}
